package cn.tianyigps.tianyigpspublic.mongo.dao;

import com.mongodb.client.result.DeleteResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.lang.reflect.ParameterizedType;
import java.util.List;

@Repository
public class BaseDaoImp<T> implements BaseDao<T> {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建一个 Class 的对象来获取泛型的 Class
     */
    private Class<T> clz;


    public Class<T> getClz(){
        if(clz==null){
            clz = ((Class<T>)(((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
        }
        return clz;
    }



    @Override
    public boolean remove(String id) {
        Criteria criteria = Criteria.where("_id").is(new ObjectId(id));
        Query query = new Query(criteria);
        DeleteResult deleteResult =  mongoTemplate.remove(query, getClz());
        return  deleteResult.getDeletedCount()> 0 ? true :false;
    }

    @Override
    public T get(String id) {
        Criteria criteria = Criteria.where("_id").is(id);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, getClz());
    }

    @Override
    public T find(String equipmentId) {
        Criteria criteria = Criteria.where("equipmentId").is(equipmentId);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, getClz());
    }

    @Override
    public void insert(T t) {
        mongoTemplate.insert(t);
    }

    @Override
    public void insert(List<T> t) {
        mongoTemplate.insert(t);
    }

    @Override
    public void insert(T t, String collectionName) {
        mongoTemplate.insert(t,collectionName);
    }

    @Override
    public void insert(List<T> t, String collectionName) {
        mongoTemplate.insert(t,collectionName);
    }

    @Override
    public void save(T t) {
        mongoTemplate.save(t);
    }

}
